import { createRouter, createWebHistory } from 'vue-router'
import Cookies from 'js-cookie'
import { useMainStore } from '@/stores/mainStore'
import { isEqual } from 'es-toolkit'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'Index',
      redirect: '/login',
      component: () => import('@/components/Index.vue'),
      children: [
        {
          path: '/redirect/:redirect',
          name: 'Redirect',
          redirect: (to) => {
            return { path: `${to.params.redirect}` }
          }
        },
        {
          path: '/profile',
          name: 'MyProfile',
          component: () => import('@/views/UserProfile.vue')
        },
        {
          path: '/passwd',
          name: 'Passwd',
          component: () => import('@/views/Passwd.vue')
        }
      ]
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue')
    }
  ]
})

let children: Menu[]

router.beforeEach((to) => {
  const token = Cookies.get('quicklyToken')
  if ('/login' === to.path) {
    // 前往登录页放行
    return true
  }
  if (!token) {
    // 或者不是登录页 并且没有 token 跳转到 登录页
    ElMessage({
      message: '登录状态过期, 请重新登录',
      type: 'info',
      grouping: true,
      duration: 1500
    })

    sessionStorage.setItem('lastPath', window.location.pathname)
    sessionStorage.setItem('lastPathQuery', window.location.search)

    return {
      path: '/login'
    }
  }

  const mainStore = useMainStore()
  // 获取路径
  const toPath = to.path
  mainStore.currentPath = { path: toPath, query: to.query }

  const child = children.find((child) => child.routerPath === toPath)

  if (child && toPath !== mainStore.firstChildMenu?.routerPath) {
    const flag = mainStore.routeTags.find(
      // 路径和查询参数一样
      (item) => item.path === toPath && isEqual(item.query, to.query)
    )
    if (!flag) {
      mainStore.routeTags.push({ name: child.menuName, path: child.routerPath, query: to.query })
    }
  }
})

export default router

export async function addDynamicRoute(menus: Menu[] | undefined) {
  const vues = import.meta.glob('../views/**/*.vue')
  if (!menus) return
  findAllChildren(menus)

  for (let index = 0; index < menus.length; index++) {
    const element = menus[index]
    if (element.menuType === 'M') {
      const r = {
        path: element.routerPath,
        name: element.routerName,
        component: vues['../views/' + element.componentPath + '.vue'],
        redirect: undefined,
        children: undefined,
        meta: {
          menuNames: [element.menuName]
        }
      }
      router.addRoute('Index', r)
    } else if (element.menuType === 'D') {
      for (let index = 0; index < element.children.length; index++) {
        const child = element.children[index]
        const r = {
          path: element.routerPath + child.routerPath,
          name: child.routerName,
          component: vues['../views/' + child.componentPath + '.vue'],
          redirect: undefined,
          children: undefined,
          meta: {
            menuNames: [element.menuName, child.menuName]
          }
        }
        router.addRoute('Index', r)
      }
    }
  }

  const c = async () => await import(/* @vite-ignore */ '../components/NotFount.vue')
  const notFound = {
    path: '/notfount',
    name: 'NotFount',
    component: c,
    redirect: undefined,
    children: undefined,
    meta: {
      menuNames: ['404']
    }
  }
  router.addRoute('Index', notFound)

  const NotFountPages = {
    path: '/:pathMatch(.*)*',
    name: 'NotFountPages',
    component: undefined,
    redirect: '/notfount',
    children: undefined
  }
  router.addRoute('Index', NotFountPages)
}

// 查找所有子菜单
function findAllChildren(menus: Menu[]) {
  const temp: Menu[] = []
  menus.forEach((father) => {
    const fatherPath = father.routerPath
    if (father.children && father.children.length > 0) {
      father.children.forEach((child) => {
        const newChild: Menu = { ...child }
        const childPath = child.routerPath
        newChild.routerPath = fatherPath + childPath
        temp.push(newChild)
      })
    } else if (father.menuType == 'M') {
      // 如果父本来就是菜单类型
      temp.push(father)
    }
  })
  const mainStore = useMainStore()
  // 保存第一个菜单
  mainStore.firstChildMenu = temp[0]
  children = temp
}
